package com.myopen.controller.admin;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.core.ActionKey;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.myopen.base.BaseController;
import com.myopen.base.BaseDataTableVo;
import com.myopen.base.BaseVo;
import com.myopen.config.ConstConfig;
import com.myopen.model.Attr;

public class AttrController extends BaseController{
	
	@ActionKey("/admin/shop/attr")
	public void index(){
		render("/admin/shop/attr/index.html");
	}
	
	@ActionKey("/admin/shop/attr/pagequery")
	public void pagequery(){
		
		Record record=getSearchRecord();//会自动组装通用的参数
		record.set("searchContent", getPara("searchContent"));
		Page<Record> page=Attr.dao.pagequery(record);
		
		BaseDataTableVo tableVo=new BaseDataTableVo(page);
		renderJson(tableVo);
	}

	@ActionKey("/admin/shop/attr/add")
	public void add(){
		
		List<Record> attrValues=new ArrayList<>();
		attrValues.add(new Record());
		Record vo=new Record();
		vo.set("attrValues", attrValues);

		setAttr("vo", vo);//有时候需要事先编一个号，这样比较方便
		setAttr(ConstConfig.ACTION_TYPE, ConstConfig.ACTION_TYPE_ADD);
		render("/admin/shop/attr/detail.html");
	}

	@ActionKey("/admin/shop/attr/view")
	public void view(){
		String id=getPara("id");
		Record vo=Attr.dao.getRecordById(id);

		List<Record> attrValues=vo.get("attrValues");
		if(attrValues.size()==0){
			attrValues.add(new Record());
		}

		setAttr("vo", vo);
		setAttr(ConstConfig.ACTION_TYPE, ConstConfig.ACTION_TYPE_VIEW);
		render("/admin/shop/attr/detail.html");
	}
	
	@ActionKey("/admin/shop/attr/save")
	public void save(){
		
		BaseVo baseVo=new BaseVo();
		Record currUser=getAdminUser();
		
		String id=getPara("id");
		String categoryId=getPara("categoryId");
		String attrname=getPara("attrname");
		String attrcode=getPara("attrcode");
		String attrdesc=getPara("attrdesc");

		String[] valueids=getParaValues("valueid");
		String[] values=getParaValues("value");
		String[] valuecodes=getParaValues("valuecode");
		String[] valuedesps=getParaValues("valuedesp");
		String[] valuepxs=getParaValues("valuepx");
		
		Record vo=new Record();
		vo.set("id", id);
		vo.set("categoryId", categoryId);
		vo.set("name", attrname);
		vo.set("code", attrcode);
		vo.set("desp", attrdesc);

		List<Record> attrValues=new ArrayList<>();
		for(int i=0;i<valueids.length;i++){
			Record attrValue=new Record();
			attrValue.set("id", valueids[i]);
			attrValue.set("value", values[i]);
			attrValue.set("code", valuecodes[i]);
			attrValue.set("desp", valuedesps[i]);
			attrValue.set("px", valuepxs[i]);
			attrValues.add(attrValue);
		}

		vo=Attr.dao.save(vo,attrValues,currUser);
		Record data=new Record();

		data.set("vo", vo);
		baseVo.setData(data);
		
		renderJson(baseVo);
	}
}
